package com.zygh.lz.controller.app;

import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.zygh.lz.constant.HttpClient;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.dao.VerifyBeanMapper;
import com.zygh.lz.entity.Information;
import com.zygh.lz.entity.InformationUser;
import com.zygh.lz.entity.bean.*;
import com.zygh.lz.service.InformationService;
import com.zygh.lz.service.impl.InformationUserService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysPcLog;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Api(tags = "APP消息推送", description = "APPPushNotifications")
@RestController
public class APPPushNotifications {

    @Resource
    private VerifyBeanMapper verifyBeanMapper;
    @Resource
    private InformationUserService informationUserService;
    @Resource
    private InformationService informationService;

    private static String appID = "0f71c85ac5ee4edba0599d96925bd357";
    private static String appKey = "627d8e6406244278ab25d197743d39f5";
    private static String appPkg = "com.appler.zygh_mobilepatrol";
    private static String appOwner = "河南中裕广恒科技股份有限公司";
    private static String appName = "交管警务";

    private static final String TOKEN = "DCDD1DA1E2C6DE4176FA6A23B8F04032A7F17D2824F4103AFE943504B09006E8";

/*    public static void main(String[] args) {
		HttpTest.sendPushMsgByToken();//通过token调用推送消息接口
		HttpTest.sendPushMsgBySign();//通过sign调用推送消息接口
		HttpTest.sendNoticeByToken();//通过token调用通知公告接口
		HttpTest.sendNoticeBySign();//通过sign签名调用通知公告接口
		HttpTest.share2DynamicBySign(); //通过sign签名调用分享动态接口
        HttpTest.share2DynamicByToken();//通过Token签名调用分享动态接口
		HttpTest.getToken();//测试获取token
    }

    public static void sendPushMsgBySign() {
        sendPushMsg(null);
    }*/

    /**
     * 调用token存储到本地
     */
    @GetMapping("sendPushMsgByToken")
    public void sendPushMsgByToken() {
        String result = getToken();
        TokenResultBean tokenResultBean = new Gson().fromJson(result, TokenResultBean.class);
        if (tokenResultBean != null) {
            String code = tokenResultBean.getCode();
            if (code == null) {
                log.error("获取票据失败！");
                return;
            }
            if (code.equals(TokenResultBean.Code.SUUCESS)) {
                //存入数据库
                VerifyBean verifyBean = new VerifyBean();
                verifyBean.setEffectiveTime(String.valueOf(tokenResultBean.getExpires_in()));
                verifyBean.setToken(tokenResultBean.getToken());
                verifyBean.setCreateTime(new Date());
                verifyBeanMapper.updateById(verifyBean);
                //sendPushMsg(token);
            } else {

                log.error("获取票据失败：" + tokenResultBean.getError());
            }
        } else {
            log.error("获取token失败");
        }

    }

    /**
     * 发送消息
     */
    @ApiOperation("发送消息")
    @GetMapping("sendPushMsg")
    public void sendPushMsg(ParamParameter paramParameter) {
        VerifyBean veriFyById = verifyBeanMapper.findVeriFyById();
        String token = veriFyById.getToken();
        ThirdPnMsgBean thirdPnMsgBean = new ThirdPnMsgBean();
        long timestamp = System.currentTimeMillis();
        paramParameter.setTime(timestamp);
        //paramParameter.setMsgLevel(paramParameter.getMsgLevel());
        thirdPnMsgBean.setReqType("sendPushMsg");
        ReqDataBean reqDataBean = createPushMsgParam(paramParameter);
        thirdPnMsgBean.setReqData(reqDataBean);
        String json = new Gson().toJson(thirdPnMsgBean);
        String signStr = null;
        if (token == null) {
            log.info("通过签名方式调用接口");
            String jsonstamp = json + timestamp;
            log.info("加密前：" + jsonstamp);
            signStr = SignUtil.sha256_HMAC(jsonstamp, appKey);
            log.info("加密后：" + signStr);
        }
        RequestBean<ThirdPnMsgBean> requestBean = new RequestBean<ThirdPnMsgBean>();
        requestBean.setData(thirdPnMsgBean);
        requestBean.setSign(signStr);
        requestBean.setAppId(appID);
        requestBean.setTimestamp(timestamp);
        String requestJson = new Gson().toJson(requestBean);
        String result = HttpClient.doPost("http://62.9.41.51:7070/mpp/third/message/forward", requestJson, token);
        //发送消息接收人存入数据库
        InformationUser informationUser = new InformationUser();
        informationUser.setAcceptWarningSignal(paramParameter.getWarningSignal())
                .setInformationId(paramParameter.getInformationId())
                .setIsRead(false)
                .setName(paramParameter.getName())
                .setUpdateTime(DateUtil.now());
        if (StringUtils.isEmpty(result)) {
            informationUser.setIsSuccessful(false);
            informationUserService.insert(informationUser);
            log.info("发送失败" + result);
        } else {
            JSONObject results = JSONObject.fromObject(result);
            JSONObject jsons = JSONObject.fromObject(results.get("result"));
            String flag = jsons.get("flag").toString();
            if ("1".equals(flag)) {
                log.info("发送成功"+results);
                informationUser.setIsSuccessful(true);
                informationUserService.insert(informationUser);
                //log.info(insert + "发送的数据：" + requestJson);
            } else {
                informationUser.setIsSuccessful(false);
                informationUserService.insert(informationUser);
                log.error("发送失败"+results);
            }
        }

    }

    /**
     * 请求结果：：{"appId":"0f71c85ac5ee4edba0599d96925bd357","result":{"flag":"1","message":"请求成功"},"sign":"CCF54A3BB32D80C6B24AA06D0C8FC279C5DDAECBEA37C6A2EE792D8C9EBD5E5C","timestamp":1638406254800}
     * <p>
     * <p>
     * <p>
     * 发送数据示例：{"appId":"0f71c85ac5ee4edba0599d96925bd357",
     * "data":{"reqType":"sendPushMsg",
     * "reqData":{"msgID":"887c8580-4a47-47c5-be45-7a89086be59d","appName":"交管警务",
     * "appOwner":"河南中裕广恒科技股份有限公司","appPkg":"com.appler.zygh_mobilepatrol","receiverCodes":"100728",
     * "param":"%7B%22id%22%3A%224a8b3fec565046d88f23872d07db11b2%22%2C%22name%22%3A%22%E5%BC%A0%E5%A4%84%22%2C%22content%22%3A%22%E5%91%A8%E4%BA%94%E4%B8%8B%E5%8D%882%E7%82%B9%E5%BC%80%E5%91%A8%E4%BC%9A%22%7D",
     * "msgdigest":"收到消息请回复","msgType":1,"sendTime":1638233367921}},"timestamp":1638233367921}
     *
     * @param paramParameter 入参
     */
    @ApiOperation("批量发送消息")
    @PostMapping("batchSendPushMsg")
    public ResultBean batchSendPushMsg(@RequestBody ParamParameter paramParameter) {
        List<Entrance> entrances = paramParameter.getEntrances();
        //插入消息
        //发送消息存入本地
        Information information = new Information();
        information.setSendWarningSignal(paramParameter.getSendWarningSignal())
                .setMsgdigest(paramParameter.getMsgdigest())
                .setTitle("交管警务-" + paramParameter.getTitle())
                .setCreatTime(DateUtil.now())
                .setMsgLevel(paramParameter.getMsgLevel());
        int insert = informationService.insert(information);
        int id = information.getId();
        if (insert == 1) {
            for (Entrance entrance : entrances) {
                paramParameter.setWarningSignal(entrance.getSendWarningSignal())
                        .setName(entrance.getName())
                        .setInformationId(id);
                sendPushMsg(paramParameter);
            }
            return ResultUtil.setOK("success", null);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);

    }

    @ApiOperation("查询消息历史")
    @GetMapping("findPushHistory")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "Integer", required = true)

    })
    public ResultBean findPushHistory(Pushsource pushsource) {
        return informationService.findPushHistory(pushsource);
    }




    private static ReqDataBean createPushMsgParam(ParamParameter paramParameter) {
        ReqDataBean reqDataBean = new ReqDataBean();
        reqDataBean.setAppName(appName);
        reqDataBean.setAppOwner(appOwner);
        reqDataBean.setAppPkg(appPkg);
        reqDataBean.setTitle("交管警务-" + paramParameter.getTitle());
        reqDataBean.setMsgdigest(paramParameter.getMsgdigest());
        reqDataBean.setMsgLevel(paramParameter.getMsgLevel());
        //actionUrl如果为空，门户将根据appPkg将应用启动起来，同样可以在被启动的那个activity页面通过intent接收param参数
        //reqDataBean.setActionUrl("com.xdja.jwt.test");
        reqDataBean.setMsgID(UUID.randomUUID().toString());
        reqDataBean.setMsgType(1);
//        try {
//            //reqDataBean.setParam(URLEncoder.encode(getParam(), "utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        reqDataBean.setReceiverCodes(paramParameter.getWarningSignal());
        reqDataBean.setSendTime(paramParameter.getTime());
        return reqDataBean;
    }

    /**
     * 返回示例
     * {"code":"1","expires_in":7200,"token":"DCDD1DA1E2C6DE4176FA6A23B8F04032A7F17D2824F4103AFE943504B09006E8"}
     *
     * @return String
     */
    public static String getToken() {
        TokenRequestBean requestBean = new TokenRequestBean();
        requestBean.setAppId(appID);
        requestBean.setAppKey(appKey);
        String json = new Gson().toJson(requestBean);
        String result = HttpClient.doPost("http://62.9.41.51:7070/mpp/third/get_token", json, null);
        log.info("获取token入参：" + json);
        log.info("获取token结果：" + result);
        return result;
    }

    /**
     * 获取参数
     *
     * @return String
     */

    public static String getParam() {
        ParamBean paramBean = new ParamBean();
        paramBean.setContent("周五下午2点开周会");
        paramBean.setId("4a8b3fec565046d88f23872d07db11b2");
        paramBean.setName("张处");
        return new Gson().toJson(paramBean);

    }

    public static void main(String[] args) {
        TokenRequestBean requestBean = new TokenRequestBean();
        requestBean.setAppId(appID);
        requestBean.setAppKey(appKey);
        String json = new Gson().toJson(requestBean);
        System.out.println(json);
    }


}
